<?php

namespace App\Models;

use App\Events\SellChange;

class Sell extends BaseModel
{

  protected $table = 'sell';
  public $incrementing = false;
  protected $keyType = 'string';
  protected $guarded = [];

  protected $casts = [
    'took_at' => 'datetime:Y-m-d H:i',
    'done_at' => 'datetime:Y-m-d H:i',
    'coins' => 'float',
    'fee' => 'float',
    'tip' => 'float',
  ];

  public function scopeWhenSellerName($q, $name)
  {
    $q->when($name, function ($q) use ($name) {
      $q->whereHas('seller', function ($q) use ($name) {
        $q->where('username', $name);
      });
    });
  }

  public function scopeState($q, $state)
  {
    $q->where('state', $state);
  }

  public function seller()
  {
    return $this->belongsTo(User::class, 'seller_id');
  }

  public function member()
  {
    return $this->belongsTo(User::class, 'member_id');
  }

  public function ifLockEnoughTime()
  {
    $diff = now()->diffInHours($this->updated_at);
    $minutes = (int)System::where('key', 'sell_lock_minues')->value('value');

    if ($diff < $minutes) {
      return;
    }
    \DB::transaction(function () {
      $this->lockForUpdate();
      $this->seller_id = null;
      $this->state = 'pass';
      $this->save();

      event(new SellChange($this->id, 'unlock'));
    });
  }
}
